package com.mogician.rabbitmq_demo.service;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mogician.rabbitmq_demo.Func;
import com.mogician.rabbitmq_demo.bean.MyMessage;

import java.io.IOException;
import java.net.Socket;

public class TcpClientThread extends Thread
{
    public static final int PORT = 8890;
    public static final String HOST = "10.0.2.2";

    private Socket socket = null;

    private MyMessage receiveMsg;

    private ObjectMapper mapper;

    private Func function;

    public TcpClientThread(Func function)
    {
        this.function = function;
    }

    @Override
    public void run()
    {
        try
        {
            socket = new Socket(HOST, PORT);
            mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
            mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
            while (true)
            {
                if((receiveMsg = mapper.readValue(socket.getInputStream(), MyMessage.class))!= null)
                {
                    function.func(receiveMsg);
                }
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void sendMsg(String content)
    {
        new Thread(()->
        {
            try
            {
                mapper.writeValue(socket.getOutputStream(), new MyMessage(getID(), content));
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }).start();
    }

    public void sendMsg(MyMessage msg)
    {
        //不能在android主线程上进行网络连接，要开个线程
        new Thread(()->
        {
            try
            {
                mapper.writeValue(socket.getOutputStream(), msg);
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }).start();
    }

    public MyMessage getReceiveMsg()
    {
        return receiveMsg;
    }

    public String getID()
    {
        return socket.getLocalAddress() + ":" + socket.getLocalPort();
    }
}